package io.geekidea.boot.util.StringUtils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class JsonSpliceUtil {

    @Value("${ding-talk.attachment}")
    private  String attachment;

    private static String staticAttachment;
    @PostConstruct
    public void init() {
        staticAttachment = this.attachment;
    }

    /**
     * 拼接目标JSON
     * @param downloadUrl
     * @param name
     * @param ext
     * @return 目标JSON
     * @throws JsonProcessingException
     */
    public static String buildTargetJson(String downloadUrl, String name, String ext) throws JsonProcessingException {
        // 1. 初始化Jackson核心工具类
        ObjectMapper objectMapper = new ObjectMapper();
        
        // 2. 构造外层JSON对象（根节点）
        ObjectNode rootNode = objectMapper.createObjectNode();
        
        // 3. 构造内层数组（key=attachmentField_mf24jkvu对应的值是数组）
        ArrayNode attachmentArray = objectMapper.createArrayNode();
        
        // 4. 构造数组中的单个对象，并设置子字段
        ObjectNode attachmentItem = objectMapper.createObjectNode();
        attachmentItem.put("downloadUrl", downloadUrl);
        attachmentItem.put("name", name);
        attachmentItem.put("url", downloadUrl);
        attachmentItem.put("ext", ext);
        
        // 5. 将单个对象添加到数组中
        attachmentArray.add(attachmentItem);
        
        // 6. 给根节点设置固定key，值为上述数组
        rootNode.set(staticAttachment, attachmentArray);
        
        // 7. 转换为JSON字符串（true表示格式化输出，便于阅读；false表示压缩输出）
        return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode);
    }
}